package cn.gailvlun.gll.presentation.chat.vm

import android.arch.lifecycle.ViewModel
import cn.gailvlun.gll.chatlib.db.ChatDB2
import cn.gailvlun.gll.net.base.friend.FriendNotification
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.realm.Realm
import io.realm.RealmResults
import java.util.concurrent.TimeUnit


class FriendNotificationViewModel: ViewModel {

    private var realm: Realm?
    var friendNotificationFlowable: Flowable<RealmResults<FriendNotification>>

    constructor() : super() {
        this.realm = Realm.getInstance(ChatDB2.getConfiguration())

        friendNotificationFlowable = realm!!.where(FriendNotification::class.java)
                .findAllAsync()
                .asFlowable()
                .filter { it.isLoaded }
                .sample(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
    }

    fun saveFriendNotification(item: FriendNotification) {
        realm!!.executeTransaction { realm ->
            realm.insertOrUpdate(item)
        }
    }

    fun alreadyFriend(item: FriendNotification) {
        realm!!.executeTransaction { realm ->
            item.status = 1
            realm.insertOrUpdate(item)
        }
    }

    override fun onCleared() {
        realm?.close()
        realm = null

        super.onCleared()
    }
}